package com.ld.poetry.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.ld.poetry.config.PoetryResult;
import com.ld.poetry.service.DataReceivedCallback;
import com.ld.poetry.service.impl.QianwenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 新增功能，阿里云通义千问AI接口
 * created by vital on 2024/11/18 下午5:44
 */
@Slf4j
@RestController
public class QianwenController {

    @Resource
    private QianwenService qianwenService;

    // 系统消息
    private static final String SystemMessage = "你是一个文章总结助手，请根据发送的文章给出总结概况。";


    /**
     * 聊天接口，消息以sse发送
     * @param message 提问的问题
     * @param response 响应对象
     */
    @GetMapping("/public/chat/qianwen")
    public void chatWithQianwen(String message, HttpServletResponse response) {

        // 设置响应头以支持SSE（Server-Sent Events）
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");


        //初始化Generation实例gen和Message实例userMsg
        Generation gen = new Generation();
        // 系统消息
        Message systemMsg = Message.builder().role(Role.SYSTEM.getValue()).content(SystemMessage).build();
        // 用户消息
        Message userMsg = Message.builder().role(Role.USER.getValue()).content(message).build();


        try {
            PrintWriter writer = response.getWriter();
            // 实现DataReceivedCallback接口，并处理每次接收到的数据，将消息返回
            qianwenService.streamCallWithCallback(gen, systemMsg, userMsg, new DataReceivedCallback() {
                @Override
                public void onDataReceived(String newData) {
                    // 接收并打印新数据
                    System.out.print(newData);
                    // 数据发送
                    // 使用SSE
                    writer.write("data: " + newData + "\n\n");
                    //writer.write(newData);
                    writer.flush(); // 强制立即将缓冲区的内容写入输出流并清空缓冲区
                }
                @Override
                public void onProcessCompleted(String fullContent) {
                    // 处理完整内容，
                    System.out.println("AI聊天完整内容已发送完毕");
                }

                @Override
                public void onError(Exception error) {
                    // 错误处理
                    System.err.println(" 错误： " + error.getMessage());
                    writer.write("error");
                    writer.flush();
                    writer.close();
                    return;
                }
            });
            // 结束时，客户端连接断开
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
